import requests
from .utils import callback_log
import threading
import time


class BaseCallback(object):
    url = None
    post_data = None

    def get_salesman_instance(self):
        assert self.url is not None, (
            "必须包含url"
        )
        return self.url

    def get_post_data(self):
        assert self.post_data is not None, (
            "class里必须包含post_data"
        )
        return self.post_data

    @callback_log("post")
    def callback(self):
        response = requests.post(
            url=self.url,
            json=self.get_post_data(),
            verify=False
        )
        res_content = response.content
        return res_content, self.url, self.post_data


class VisitRecord(BaseCallback):
    def __init__(self, single_obj):
        self.single_obj = single_obj
        self.get_post()

    def get_post(self):
        # from apps.sales_man.models import Single
        # single_obj = Single.objects.get(id=1)
        self.url = self.single_obj.b_user.channel.callback
        if self.url:  # 如果配置了回调链接就回调
            product_name = self.single_obj.product.name
            username = self.single_obj.applicant.name
            tel = self.single_obj.applicant.tel
            encrypt_tel = "%s****%s" % (tel[:3], tel[-4:])  # 加密手机号
            card = self.single_obj.applicant.card
            encrypt_card = "%s****%s" % (card[:4], card[-4:])  # 加密身份证号
            visit_date_time = self.single_obj.create_time.strftime("%Y-%m-%d %H:%M:%S")  # 申请日期
            self.post_data = {
                "tel": encrypt_tel,
                "identityCard": encrypt_card,
                "visitDateTime": visit_date_time,
                "productName": product_name,
                "username": username,
            }
            if self.single_obj.t_user:
                self.post_data["referee"] = self.single_obj.t_user.name
            return self.post_data

    def visit_post(self):
        for i in range(3):
            res_content = self.callback()
            if res_content == "SUCCESS" or res_content == b'SUCCESS' or res_content == str("SUCCESS"):
                break
            time.sleep(5)

    def start_thread(self):
        threading.Thread(target=self.visit_post).start()
